package com.yanboo.modules.mnt.websocket.processor;

import com.alibaba.fastjson.JSON;
import com.yanboo.modules.mnt.websocket.processor.dto.ProcessorWSMsgDto;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;

@Slf4j
@Component
@ServerEndpoint("/ws/processor")
public class StatusWSService {

    static CopyOnWriteArrayList<Session> sessions = new CopyOnWriteArrayList<>();

    @OnOpen
    public void onOpen(Session session) throws IOException {
        sessions.add(session);
    }

    @OnClose
    public void onClose(CloseReason closeReason, Session session) {
        log.info("[websocket] 连接断开：id={}，reason={}", session.getId(), closeReason.getReasonPhrase());
        sessions.remove(session);
    }


    // 连接异常
    @OnError
    public void onError(Throwable throwable, Session session) throws IOException {
        log.info("[websocket] 连接异常：id={}，throwable={}", session.getId(), throwable.getMessage());
        sessions.remove(session);
        // 关闭连接。状态码为 UNEXPECTED_CONDITION（意料之外的异常）
        session.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, throwable.getMessage()));
    }


    public static void sendMsg(Long id, ProcessorWSMsgDto message) {
        String jsonString = JSON.toJSONString(message);
        sessions.forEach(x -> {
            try {
                x.getBasicRemote().sendText(jsonString);
            } catch (IOException e) {
                log.error("websocket send error:" + jsonString, e);
            }
        });
        log.info("websocket send message:" + jsonString);
    }

}
